<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { getCartCountApi } from '@/apis/cart';
import { getGoodsByIdApi } from '@/apis/goods'
import { sameGoodsApi } from '@/apis/search';
import type { SkuInfo } from '@/types/SkuModule';
import { useMemberStore } from '@/stores';
import type { Goods } from '@/types/Goods';
import { addCartApi } from '@/apis/cart';
import { onLoad, onShow }from'@dcloudio/uni-app';
import { addCollectApi, isCollectApi, deleteCollectApi } from '@/apis/collect';

// 安全距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 接收跳转数据
const query = defineProps<{
  skuId: number,
}>()

// 数据
const goodsInfo = ref<Goods>()
const getGoodsById = async () => {
  const res = await getGoodsByIdApi(query.skuId)
  goodsInfo.value = res.data
}

// 同类推荐
const sameData = ref<SkuInfo[]>([])
const getSameGoodsData = async () => {
  const res = await sameGoodsApi(goodsInfo.value?.skuInfo.spuId!, goodsInfo.value?.skuInfo.categoryId!)
  sameData.value = res.data;
}

// 获取购物车数量
const useMember = useMemberStore()
const count = ref<number>(0)
const getCartCount = async () => {
  const res = await getCartCountApi()
  count.value = res.data;
}

// 判断是否收藏该商品
const collect = ref<Boolean>(false)
const getIsCollect = async () => {
  const res = await isCollectApi(goodsInfo.value?.skuInfo.spuId!)
  collect.value = res.data;
}

// 选中的数量
const skuNum = ref<number>(1)

// 富文本图片处理
const handleImg = (img: any) => {
  if (img) {
    return img.replace(/\<img/gi, '<img class="rich-img"');
  }
  return;
}

// 轮播图交互
const currentIndex = ref(0)
const onChange: UniHelper.SwiperOnChange = (ev) => {
  currentIndex.value = ev.detail.current
}

// 点击图片时
const onTapImage = (url: string) => {
  // 大图预览
  uni.previewImage({
    current: url,
    urls: goodsInfo.value!.images,
  })
}

// 弹出层组件
const popup = ref<{
  open: (type?: UniHelper.UniPopupType) => void
  close: () => void
}>()

// 弹出层条件渲染
const popupName = ref<'joinCart' | 'buy' | 'seckill'>()
const openPopup = (name: typeof popupName.value) => {
  if (!useMember.profile?.token) {
    uni.navigateTo({
      url: '/pages/login/login'
    });
  } else {
    // 修改弹出层名称
    skuNum.value = 1;
    popupName.value = name;
    popup.value?.open()
  }
}

// 选中的值
const selectData = ref<string[]>([])

// 选择的商品
const handleSelect = (skuIds: any, skuId: any, index: any) => {
  if (skuIds.split(',').includes(skuId.toString())) {
    selectData.value[index] = skuIds;
    return true;
  } else {
    return false;
  }
}

// 切换skuId
const handleChange = async (skuIds: any, index: any) => {
  selectData.value[index] = skuIds;
  var skus = new Array();
  selectData.value.forEach(item => skus.push(item.split(',')));
  var filterEl = skus[0]
  for (var i = 1; i < skus.length; i++) {
    filterEl = filterEl.filter((item: string) => skus[i].includes(item))
  }
  const res = await getGoodsByIdApi(parseInt(filterEl[0]))
  skuNum.value = 1;
  goodsInfo.value = res.data;
}

// 加入购物车
const handleJoinCart = () => {
  addCartApi({
    skuId: goodsInfo.value?.skuInfo.skuId!,
    count: skuNum.value,
    selected: true
  })
    .then(res => {
      if (res.code === 0) {
        uni.showToast({
          title: '添加购物车成功',
          icon: 'none',
        })
        getCartCount()
      }
    })
  popup.value?.close()
}

// 收藏
const handleCollect = (type: number) => {
  if (!useMember.profile?.token) {
    uni.navigateTo({
      url: '/pages/login/login'
    });
  }else{
    if (type === 0) {
    addCollectApi(goodsInfo.value?.skuInfo.spuId!)
      .then(res => {
        if (res.code === 0) {
          uni.showToast({
            title: '添加收藏成功',
            icon: 'none',
          })
          collect.value = !collect.value
        }
      })
  } else {
    deleteCollectApi([goodsInfo.value?.skuInfo.spuId!])
      .then(res => {
        if (res.code === 0) {
          uni.showToast({
            title: '取消收藏成功',
            icon: 'none',
          })
          collect.value = !collect.value
        }
      })
  }
  }
}

// 立即购买按钮
const handleToBuy = () => {
  // 立即购买
  uni.navigateTo({url:`/pagesOrder/order/order?skuId=${goodsInfo.value?.skuInfo.skuId}&count=${skuNum.value}&type=2`})
  popup.value?.close()
}

// 立即购抢购
const handleToSeckill = () => {
  // 立即购买

  popup.value?.close()
}


onShow(() => {
  if (useMember.profile) {
    getCartCount()
  }
})

onLoad(async () => {
  await getGoodsById()
  if (useMember.profile) {
    getIsCollect()
  }
  getSameGoodsData()
})
</script>

<template>
  <scroll-view scroll-y class="viewport">
    <!-- 基本信息 -->
    <view class="goods">
      <!-- 商品主图 -->
      <view class="preview">
        <swiper circular class="swiper_css" @change="onChange">
          <swiper-item v-for="item in goodsInfo?.images" :key="item">
            <image @tap="onTapImage(item)" class="image" mode="aspectFill" :src="item" />
          </swiper-item>
        </swiper>
        <view class="indicator">
          <text class="current">{{ currentIndex + 1 }}</text>
          <text class="split">/</text>
          <text class="total">{{ goodsInfo?.images.length }}</text>
        </view>
      </view>
    </view>

    <!-- 商品简介 -->
    <view class="content current_css">
      <view class="price">
        <text class="symbol">¥</text>
        <text class="number">{{ goodsInfo?.skuInfo.price.toFixed(2) }}</text>
      </view>
      <view class="name ellipsis">{{ goodsInfo?.skuInfo.skuTitle }}</view>
      <view class="sub_css"> {{ goodsInfo?.skuInfo.subTitle }} </view>
        <!-- <view class="price" v-if="goodsInfo?.seckillSkuInfo === null">
          <text class="symbol">¥</text>
          <text class="number">{{ goodsInfo?.skuInfo.price.toFixed(2) }}</text>
        </view>

          <view v-else style="display: flex;justify-content: space-between;">
            <view style="display: flex;justify-content: start;">
              <view class="price" style="padding: 15rpx 20rpx 0;">
              <text class="symbol">¥</text>
              <text class="number">{{ goodsInfo?.seckillSkuInfo.seckillPrice.toFixed(2) }}</text>
            </view>
            <view class="price" style="color: gray;line-height: 2.3;padding: 15rpx 2rpx 0;">
              <text class="symbol" style="text-decoration: line-through;">原价¥</text>
              <text class="number" style="text-decoration: line-through;font-size: 32rpx;">{{ goodsInfo?.skuInfo.price.toFixed(2)}}</text>
            </view>
            </view>
            <view class="price" style="color: gray;line-height: 2.3;padding: 15rpx 6rpx 0;">
              {{ goodsInfo?.seckillSkuInfo.randomCode? '正在秒杀':`${goodsInfo?.seckillSkuInfo.startTime}开始抢购` }}
            </view>
          </view>
      <view class="name ellipsis">{{ goodsInfo?.skuInfo.skuTitle }}</view>
      <view class="sub_css"> {{ goodsInfo?.skuInfo.subTitle }} </view> -->
    </view>

    <!-- 操作面板 -->
    <view class="action current_css">
      <view class="item arrow">
        <text class="label">促销</text>
        <text class="text ellipsis"> jjjjj </text>
      </view>
    </view>

    <!-- 商品参数 -->
    <view class="attr current_css">
      <view class="title">
        <text>产品参数</text>
      </view>
      <view class="properties">
        <!-- 参数详情 -->
        <view class="item" v-for="item in goodsInfo?.spuAttributes" :key="item.attributeName">
          <text class="label">{{ item.attributeName }}</text>
          <text class="value">{{ item.value }}</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="introduce">
      <view class="desc_title">详情介绍</view>
      <view class="desc">
        <rich-text :nodes="handleImg(goodsInfo?.spuDesc)"></rich-text>
      </view>
    </view>

    <!-- 同类推荐 -->
    <view class="similar panel">
      <view class="title">
        <text class="text-title">同类推荐</text>
      </view>
      <view class="content" v-if="sameData.length > 0">
        <navigator v-for="item in sameData" :key="item.skuId" class="goods" hover-class="none"
          :url="`/pages/goods/goods?skuId=${item.skuId}`">
          <image class="image" mode="aspectFill" :src="item.skuDefaultImg"></image>
          <view class="name ellipsis">{{ item.spuTitle }}</view>
          <view class="price">
            <text class="symbol">¥</text>
            <text class="number">{{ item.price }}</text>
          </view>
        </navigator>
      </view>
      <view v-else class="content">
        <view style="height: 340rpx;width: 100%;text-align: center;background-color: white;border-radius: 10rpx;">
          <image src="../../static/images/no-data.png" mode="scaleToFill" style="height: 280rpx;width: 320rpx;"/>
          <view class="none_tip">暂无同类商品</view>
        </view>
      </view>

    </view>
  </scroll-view>

  <!-- 用户操作 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="icons">
      <button v-if="collect" class="icons-button" @tap="handleCollect(1)">
        <text class="icon-shoucangxuanzhong" style="color: rgba(248, 81, 51, 0.918);"></text>已收藏
      </button>
      <button v-if="!collect" class="icons-button" @tap="handleCollect(0)">
        <text class="icon-shoucang3" style="color: black;"></text>收藏
      </button>
      <button class="icons-button" open-type="contact">
        <text class="icon-kefu"></text>客服
      </button>
      <navigator class="icons-button" url="/pages/cart/cartBack">
          <view  v-if="count > 0" class="badge-left">{{ count }}</view>
          <text class="icon-gouwuche"></text>购物车
      </navigator>
    </view>
    <view class="buttons">
        <view class="addcart" @tap="openPopup('joinCart')">加入购物车</view>
        <view class="buynow" @tap="openPopup('buy')">立即购买</view>
        <!-- <view v-if="goodsInfo?.seckillSkuInfo?.randomCode === null" class="buynow" @tap="openPopup('buy')">立即购买</view> -->
        <!-- <view v-else class="buynow" @tap="openPopup('seckill')">立即抢购</view> -->
    </view>
  </view>

  <!-- 弹出层 -->
  <uni-popup ref="popup" type="bottom" class="popup_css">
    <view class="popup_content">
      <view class="sku_css">
        <view class="img_view">
          <image :src="goodsInfo?.skuInfo.skuDefaultImg" mode="scaleToFill" />
        </view>
        <view class="desc_content">
          <view class="sku_title">
            {{ goodsInfo?.skuInfo.skuTitle }}
          </view>
          <view class="sku_price">
            <text class="symbol">¥</text>
            <text class="number">{{ goodsInfo?.skuInfo.price }}</text>
          </view>
        </view>
      </view>
      <scroll-view scroll-y class="popup_scroll">
        <view class="goods_content" v-for="(item, index) in goodsInfo?.saleAttributes" :key="item.attributeId">
          <view><text class="attr_name">{{ item.attributeName }}</text></view>
          <view class="select_sale">
            <view v-for="el  in item.values" :key="el.value">
              <view class="sale_item" v-if="handleSelect(el.skuIds, goodsInfo?.skuInfo.skuId, index)"
                style="background-color: #fad8d6;border: 1px #e43d33 solid;">{{ el.value }}</view>
              <view class="sale_item" v-else style="background-color: #e4e5e7" @tap="handleChange(el.skuIds, index)">{{
                el.value }}</view>
            </view>
          </view>
        </view>
        <view class="num_input">
          <view>数量</view>
          <uni-number-box v-model="skuNum" :step="1" :min="1" :max="goodsInfo?.stock" />
        </view>
      </scroll-view>
      <view class="view_button">
        <!-- <button v-if="goodsInfo?.stock! > 0 && popupName === 'joinCart' && goodsInfo?.seckillSkuInfo.randomCode === null" class="popup_button" @tap="handleJoinCart">
          <text>确定</text>
        </button>
        <button v-else-if="goodsInfo?.stock! > 0 && popupName === 'buy' && goodsInfo?.seckillSkuInfo.randomCode === null" class="popup_button" @tap="handleToBuy">
          <text>立即购买</text>
        </button>
        <button v-else-if="goodsInfo?.seckillSkuInfo.seckillCount! > 0 && popupName === 'seckill'" class="popup_button" @tap="handleToSeckill">
          <text>立即抢购</text>
        </button> -->
        <button v-if="goodsInfo?.stock! > 0 && popupName === 'joinCart'" class="popup_button" @tap="handleJoinCart">
          <text>确定</text>
        </button>
        <button v-else-if="goodsInfo?.stock! > 0 && popupName === 'buy'" class="popup_button" @tap="handleToBuy">
          <text>立即购买</text>
        </button>
        <button v-else class="popup_button" style="background-color: burlywood;" disabled>
          <text>已售完</text>
        </button>
      </view>
    </view>
  </uni-popup>
</template>

<style lang='scss'>
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.viewport {
  background-color: #f4f4f4;
  height: 100%;
}

// 通用
.current_css {
  margin: 15rpx;
  border-radius: 15rpx;
}

.panel {
  margin-top: 20rpx;

  .title {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 90rpx;
    line-height: 1;
    padding: 20rpx 0;
    position: relative;

    .text-title {
      padding-left: 10rpx;
      font-size: 26rpx;
    }
  }
}

// 标题
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60rpx;
  line-height: 1;
  padding: 10rpx 20rpx;
  position: relative;

  text {
    font-size: 28rpx;
    font-weight: bolder;
  }
}

.arrow {
  &::after {
    position: absolute;
    top: 50%;
    right: 30rpx;
    content: "\e64c";
    color: #ccc;
    font-family: 'iconfont' !important;
    font-size: 32rpx;
    transform: translateY(-50%);
  }
}

// 商品图集
.goods {
  background-color: #fff;

  .preview {
    position: relative;

    .swiper_css {
      height: 600rpx;
      width: 100%;
    }

    .image {
      width: 750rpx;
      height: 100%;
    }

    .indicator {
      height: 40rpx;
      padding: 0 24rpx;
      line-height: 40rpx;
      border-radius: 30rpx;
      color: #fff;
      font-family: Arial, Helvetica, sans-serif;
      background-color: rgba(0, 0, 0, 0.3);
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;

      .current {
        font-size: 26rpx;
      }

      .split {
        font-size: 24rpx;
        margin: 0 1rpx 0 2rpx;
      }

      .total {
        font-size: 24rpx;
      }
    }
  }
}

.content {
  position: relative;
  background-color: #fff;

  .price {
    height: 90rpx;
    padding: 15rpx 20rpx 0;
    font-size: 34rpx;
    color: #f04848;
    box-sizing: border-box;
  }

  .number {
    font-size: 50rpx;
  }

  .name {
    max-height: 88rpx;
    padding: 0 20rpx 5rpx;
    line-height: 1.4;
    font-weight: bolder;
    font-size: 32rpx;
    color: #333;
  }

  .sub_css {
    line-height: 1;
    padding: 20rpx 20rpx 25rpx;
    font-size: 25rpx;
    font-weight: bolder;
    color: #cf4444;
  }
}

.action {
  padding-left: 15rpx;
  background-color: white;
  .item {
    height: 90rpx;
    padding-right: 60rpx;
    border-bottom: 1rpx solid #eaeaea;
    font-size: 26rpx;
    color: #333;
    position: relative;
    display: flex;
    align-items: center;

    &:last-child {
      border-bottom: 0 none;
    }
  }

  .label {
    width: 60rpx;
    color: #898b94;
    margin: 0 16rpx 0 10rpx;
  }

  .text {
    flex: 1;
    -webkit-line-clamp: 1;
  }
}

// 商品参数
.attr {
  background-color: #fff;

  .properties {
    padding: 0 20rpx;
    margin-bottom: 30rpx;

    .item {
      display: flex;
      line-height: 2;
      padding: 10rpx 0;
      font-size: 26rpx;
    }

    .label {
      color: gray;
      width: 200rpx;
    }

    .value {
      flex: 1;
    }
  }
}

// 商品详情
.introduce {
  width: 100%;

  .desc_title {
    width: 100%;
    text-align: center;
    font-size: 26rpx;
    padding-bottom: 20rpx;
    
  }

  .desc {
    height: 100%;
    width: 100%;

    rich-text .rich-img {
      width: 100%;
      height: auto;
    }
  }
}

/* 同类推荐 */
.similar {
  .content {
    padding: 0 20rpx 206rpx;
    background-color: #f4f4f4;
    display: flex;
    flex-wrap: wrap;

    .none_tip {
      text-align: center;
      font-size: 20rpx;
      color: #666;
    }

    .goods {
      width: 340rpx;
      padding: 10rpx;
      margin: 10rpx 0;
      text-align: center;
      border-radius: 10rpx;
      background-color: #fff;
    }

    .image {
      width: 300rpx;
      height: 260rpx;
    }

    .name {
      height: 75rpx;
      font-size: 26rpx;
      color: #262626;
    }

    .price {
      line-height: 2.2;
      font-size: 32rpx;
      text-align: start;
      color: #cf4444;
    }

    .number {
      font-size: 32rpx;
      margin-left: 2rpx;
    }
  }

  navigator {
    &:nth-child(even) {
      margin-right: 0;
    }
  }
}

/* 底部工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx var(--window-bottom);
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;

  .buttons {
    display: flex;

    &>view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }

    .addcart {
      background-color: rgb(254, 201, 1);
    }

    .buynow {
      background-color: red;
      margin-left: 20rpx;
    }
  }

  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;

    .icons-button {
      flex: 1;
      position: relative;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;

      .badge-left {
        position: absolute;
        right: 16rpx;
        top: -5rpx;
        background-color: #f34646;
        height: 23rpx;
        width: 23rpx;
        border-radius: 23rpx;
        line-height: 23rpx;
        color: white;
      }

      &::after {
        border: none;
      }
    }

    text {
      display: block;
      font-size: 34rpx;
    }
  }
}

// 弹窗内容
.popup_content {
  background-color: #fff;
  height: 680rpx;
  border-top-left-radius: 30rpx;
  border-top-right-radius: 30rpx;
  padding: 30rpx 25rpx 0;

  .sku_css {
    height: 180rpx;
    width: 100%;
    display: flex;
    justify-content: center;

    .img_view {
      width: 230rpx;
      height: 100%;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .desc_content {
      width: 100%;
      height: 100%;

      .sku_title {
        height: 70%;
        padding: 10rpx;
        box-sizing: border-box;
        font-size: 28rpx;
      }

      .sku_price {
        height: 30%;
        padding: 5rpx 10rpx;
        box-sizing: border-box;
        color: red;
        font-size: 28rpx;

        .number {
          font-size: larger;
        }
      }
    }
  }

  .popup_scroll {
    width: 100%;
    height: 415rpx;

    .goods_content {
      .attr_name {
        font-size: 28rpx;
      }

      .select_sale {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;

        .sale_item {
          font-size: 30rpx;
          margin: 15rpx 30rpx 15rpx 0rpx;
          padding: 5rpx 25rpx;
          border-radius: 30rpx;
          // background-color: rgb(190, 87, 87);
        }
      }
    }
  }

  .num_input {
    display: flex;
    justify-content: space-between;
    height: 48rpx;
    font-size: 30rpx;
    margin-top: 5rpx;
  }

  .view_button {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 70rpx;
    padding-bottom: 60rpx;
  }

  .popup_button {
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    width: 90%;
    height: 70rpx;
    font-size: 32rpx;
    border-radius: 50rpx;
    background-color: rgb(248, 56, 69);
  }
}</style>